package com.omiis.wechat.performance_test2;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.commons.configuration.CompositeConfiguration;
import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class WeChatConfiguration {

	private static Logger logger = LoggerFactory.getLogger(WeChatConfiguration.class);
	private static CompositeConfiguration compositeConfiguration = new CompositeConfiguration();
	private static char delimiter_char = '`';

	public Configuration getConfiguration() {
		return compositeConfiguration;
	}

	private WeChatConfiguration() {
		initialize();
	}

	private static WeChatConfiguration singleton;

	public static WeChatConfiguration getIngleton() {
		if (singleton == null) {
			synchronized (WeChatConfiguration.class) {
				if (singleton == null) {
					singleton = new WeChatConfiguration();
				}
			}
		}
		return singleton;
	}

	private void initialize() {
		long t1 = System.currentTimeMillis();
		File settingFile = new File(IPreferences.APP_SETTING);
		if (!settingFile.exists()) {
			throw new RuntimeException("配置文件：" + settingFile.getPath() + "不存在！");
		}
		List<String> files = null;
		try {
			files = FileUtils.readLines(settingFile);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		logger.info("需加载的配置文件列表：{}", files);
		for (String fileName : files) {
			if (fileName.startsWith("#"))
				continue;
			File configFile = new File(fileName);
			logger.info("加载配置文件：{}", configFile.getPath());
			PropertiesConfiguration properties = new PropertiesConfiguration();
			try {
				properties.load(configFile);
			} catch (ConfigurationException e) {
				logger.error(e.getMessage(), e);
			}
			compositeConfiguration.setDefaultListDelimiter(delimiter_char);
			compositeConfiguration.addConfiguration(properties);
		}
		long t2 = System.currentTimeMillis();
		logger.info("加载配置文件耗时：{}毫秒。", (t2 - t1));
	}

	public String getValue(String key) {
		return getString(key, null);
	}

	public String getValue(String key, String defaultValue) {
		return getString(key, defaultValue);
	}

	public String getString(String key, String defaultValue) {
		return compositeConfiguration.getString(key, defaultValue);
	}

	public int getInt(String key) {
		return compositeConfiguration.getInt(key);
	}

	public int getInt(String key, int defaultValue) {
		return compositeConfiguration.getInt(key, defaultValue);
	}

	public String[] getStringArray(String key) {
		return compositeConfiguration.getStringArray(key);
	}
}
